package com.vinny.springbootflowable2.exception;

import com.vinny.springbootflowable2.common.constant.ApiResultCode;
import com.vinny.springbootflowable2.model.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.FlowableException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BaseException.class)
    public ApiResponse<Void> handleBaseException(BaseException e) {
        log.error("业务异常", e);
        return ApiResponse.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ApiResponse<Void> handleUnauthorizedException(UnauthorizedException e) {
        log.error("未授权异常", e);
        return ApiResponse.error(ApiResultCode.UNAUTHORIZED, e.getMessage());
    }

    @ExceptionHandler(FlowableException.class)
    public ApiResponse<Void> handleFlowableException(FlowableException e) {
        log.error("工作流异常", e);
        return ApiResponse.error(ApiResultCode.BUSINESS_ERROR, "工作流处理异常：" + e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Void> handleValidationException(MethodArgumentNotValidException e) {
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        log.error("参数校验异常: {}", errors);
        return ApiResponse.error(ApiResultCode.PARAM_ERROR, String.join(", ", errors));
    }

    @ExceptionHandler(BindException.class)
    public ApiResponse<Void> handleBindException(BindException e) {
        List<String> errors = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        log.error("参数绑定异常: {}", errors);
        return ApiResponse.error(ApiResultCode.PARAM_ERROR, String.join(", ", errors));
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<Void> handleException(Exception e) {
        log.error("系统异常", e);
        return ApiResponse.error(ApiResultCode.SERVER_ERROR, "系统异常，请联系管理员");
    }
} 